package MultiChat;
//[ek] TODO use blank line between package and import declarations
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ChatClient {
	public static void main(String[] arg) {
		ChatClient chatClient = new ChatClient();
		chatClient.execute();
	}
	
	//[ek] XXX why not static?
	public void execute() {
		try {
			//[ek] TODO make symbolic constant for value reuse
			Socket socket = new Socket(InetAddress.getByName("gerunn.ru").getHostAddress(), ChatServer.port);

			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //[ek] TODO rename to socketReder
			PrintWriter writer = new PrintWriter(socket.getOutputStream());
			BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

			ExecutorService executorService = Executors.newCachedThreadPool(); //[ek] XXX overkill?

			executorService.submit(new ChatClientServerReaderThread(this, reader));
			executorService.submit(new ChatClientConsoleReaderThread(this, consoleReader, writer));
			//[ek] TODO remove dead comments
//			while (true) {
//				while (reader.ready()) {
//					System.out.println(new Message(reader));
//				}
//
//				while (consoleReader.ready()) {
//					new Message(consoleReader).sendMessage(writer);
//				}
//
//				Thread.sleep(100);
//			}

		} catch (UnknownHostException e) {
			e.printStackTrace(); //[ek] TODO why not user-friendly message?
		} catch (IOException e) {
			e.printStackTrace();
		}
//		catch (InterruptedException e) {
//			e.printStackTrace();
//		}
	}
	
	//[ek] TODO why synchronized?
	public synchronized void show(Message message) {
		System.out.println(message);
	}
}
